package com.thoughtorigin.application {
import com.thoughtorigin.exception.MethodNotOverridenException;

import flash.display.MovieClip;
import flash.display.Sprite;
import flash.display.StageAlign;
import flash.display.StageScaleMode;
import flash.events.Event;
import flash.utils.getDefinitionByName;

/**
 * TODO find a way to test this class
 */
public class Application extends MovieClip {

    protected var mainClassName: String = "Main";
    private var _applicationSettings: ApplicationSettings;

    public function Application() {
        stop();
        addEventListener(Event.ENTER_FRAME, onEnterFrame);
    }

    private function onEnterFrame(e: Event): void {
        graphics.clear();
        if(framesLoaded == totalFrames) {
            removeEventListener(Event.ENTER_FRAME, onEnterFrame);
            nextFrame();
            onLoadComplete();
            init();
        } else {
            onProgress();
        }
    }

    protected function init(): void {
        var mainClass: Class = Class(getDefinitionByName(mainClassName));
        if(mainClass) {
            var app: Sprite = new mainClass();
            if(app is InjectPreloader) {
                InjectPreloader(app).applicationSettings = _applicationSettings;
                InjectPreloader(app).preloader = this;
            }
            addChild(app);
        }
    }

    protected function get bytesTotal(): Number {
        return root.loaderInfo.bytesTotal;
    }

    protected function get bytesLoaded(): Number {
        return root.loaderInfo.bytesLoaded;
    }

    protected function onProgress(): void {
        throw new MethodNotOverridenException("This function must be overriden");
    }

    protected function onLoadComplete(): void {
        throw new MethodNotOverridenException("This function must be overriden");
    }

    protected function preloaderComplete(): void {
        init();
    }

    protected function set applicationSettings(value: ApplicationSettings): void {
        _applicationSettings = value;
    }

}
}